//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.yonyou.ucf.mdd.ext.poi.importbiz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.cloud.middleware.rpc.RPCStubBeanFactory;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.ucf.mdd.api.dto.ImportContextDto;
import com.yonyou.ucf.mdd.api.interfaces.rpc.IPoiSupportApi;
import com.yonyou.ucf.mdd.api.interfaces.rpc.IRefApi;
import com.yonyou.ucf.mdd.common.model.uimeta.ui.ViewModel;
import com.yonyou.ucf.mdd.core.http.HttpsRequest;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.dubbo.DubboReferenceUtils;
import com.yonyou.ucf.mdd.ext.poi.context.ImportContext;
import com.yonyou.ucf.mdd.ext.poi.dto.ImportViewModelDataDto;
import com.yonyou.ucf.mdd.ext.poi.importbiz.conver.ConverService;
import com.yonyou.ucf.mdd.ext.poi.importbiz.enums.DrawDataTypeEnum;
import com.yonyou.ucf.mdd.ext.poi.importbiz.init.ImportServiceInit;
import com.yonyou.ucf.mdd.ext.poi.importbiz.pipeline.ForwardingPipeline;
import com.yonyou.ucf.mdd.ext.poi.importbiz.pipeline.PrePipelineContext;
import com.yonyou.ucf.mdd.ext.poi.importbiz.service.common.ImportRemoteCallParamHandleService;
import com.yonyou.ucf.mdd.ext.poi.importbiz.service.interf.ImportDataEventHandle;
import com.yonyou.ucf.mdd.ext.poi.importbiz.vo.ImportEvent;
import com.yonyou.ucf.mdd.ext.util.GsonExtUtils;
import com.yonyou.yonbip.iuap.xport.importing.progress.ImportProgressReporter;
import com.yonyou.yonbip.iuap.xport.importing.progress.ImportTaskLifecycle;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequest;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequestBody;
import org.apache.commons.lang3.StringUtils;
import org.imeta.biz.base.BizException;
import org.imeta.core.lang.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("uniteImportEventHandle")
public class UniteImportEventHandle implements ImportDataEventHandle {
    private static final Logger log = LoggerFactory.getLogger(UniteImportEventHandle.class);
    public static final String NAME = "uniteImportEventHandle";
    @Resource
    private ConverService converService;
    @Resource
    private ImportServiceInit importServiceInit;
    @Resource
    private ImportRemoteCallParamHandleService remoteCallParamHandleService;
    @Autowired
    protected ImportProgressReporter reporter;

    public UniteImportEventHandle() {
    }

    public void importHandleEvent(ImportContextDto contextDto, ImportEvent importEvent, Object tenantCode) throws Exception {
        String subTaskKey = importEvent.getSubKey();
        String uri = "/drawBatchData/data/{0}/{1}";
        uri = MessageFormat.format(uri, DrawDataTypeEnum.ORIGIN_DATA.getCode(), subTaskKey);
        String importTplId = contextDto.getImportTplId();
        if (StringUtils.isNotBlank(importTplId)) {
            uri = uri + "?importTplId=" + importTplId;
        }

        String url = AppContext.getEnvConfig("domain.iuap-metadata-import");
        if (StringUtils.isBlank(url)) {
            url = AppContext.getEnvConfig("mdd.applytool.net.address");
        }

        if (StringUtils.isBlank(url)) {
            throw new BizException("apply tool net address is empty");
        } else {
            url = url + uri;
            byte[] res = null;
            int i = 0;

            long startTime;
            for(startTime = System.currentTimeMillis(); i < 3; ++i) {
                if (InvocationInfoProxy.getYhtAccessToken()!=null && !InvocationInfoProxy.getYhtAccessToken().startsWith("btt")) {
                    ISVRequest isvRequest = AppContext.getBean(ISVRequest.class);
                    ISVRequestBody isvRequestBody = new ISVRequestBody();
                    isvRequestBody.setUrl(url);
                    isvRequestBody.setRequestMethod("GET");
                    Map<String, Object> mapTmp = remoteCallParamHandleService.getHeaderParam();
                    if(mapTmp == null){
                        mapTmp = new HashMap<>();
                    }
                    Map<String, String> headerParam = new HashMap<>();
                    headerParam.put("Cookie", (String) mapTmp.get("Cookie"));
                    isvRequestBody.setHeaders(headerParam);
                    String result = isvRequest.doRequest(InvocationInfoProxy.getTenantid(), isvRequestBody);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    try {
                        byteArrayOutputStream.write(result.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    res = byteArrayOutputStream.toByteArray();
//                    JSONArray resArray = (JSONArray) JSONObject.parseObject(result, Map.class).get("mapListBytes");
//                    if(resArray.size() != 0){
//                        byte[] resByte = new byte[resArray.size()];
//                        for(int j=0; j<resArray.size(); j++){
//                            Integer tmp = (Integer) resArray.get(j);
//                            resByte[j] = tmp.byteValue();
//                        }
//                        res = resByte;
//                    }
                } else {
                    res = HttpsRequest.getInstance().sendGet2ByteArray(url, this.remoteCallParamHandleService.getHeaderParam());
                }

                log.error("draw data start handle time = {}", System.currentTimeMillis() - startTime);
                if (res != null && res.length > 0) {
                    break;
                }

                try {
                    Thread.sleep(50L);
                } catch (Exception var28) {
                }
            }

            if (res != null && res.length != 0) {
                startTime = System.currentTimeMillis();
                ImportViewModelDataDto importViewModelDataDto = null;

                try {
                    importViewModelDataDto = (ImportViewModelDataDto)GsonExtUtils.getObjectByByteArray(res, ImportViewModelDataDto.class);
                } catch (Throwable var27) {
                    log.error("query import batch data error,subKey={},query result={}", new Object[]{subTaskKey, new String(res, "UTF-8"), var27});
                    throw new BizException("query result error ,result=" + new String(res, "UTF-8") + ",subkey=" + subTaskKey);
                }

                if (importViewModelDataDto == null) {
                    throw new BizException("query result error ,result=" + new String(res, "UTF-8") + ",subkey=" + subTaskKey);
                } else {
                    List<Map<String, Object>> mapList = GsonExtUtils.getListMapsByByteArray(importViewModelDataDto.getMapListBytes());
                    String redisDataKey = importEvent.getRedisDataKey();
                    ImportContext importContext = importEvent.getImportContext();
                    int totalCount = importEvent.getImportContext().getTotalCount();
                    if (mapList == null) {
                        log.error("not found volid data，redisDataKey＝{}", redisDataKey);
                        throw new BizException("msg1186210", importContext.msg1186210);
                    } else {
                        ViewModel viewModel = null;
                        byte[] viewModelBytes = importViewModelDataDto.getViewModelBytes();
                        if (viewModelBytes != null && viewModelBytes.length > 0) {
                            viewModel = (ViewModel)GsonExtUtils.getObject(new String(viewModelBytes, "UTF-8"), ViewModel.class);
                        }

                        this.reporter.updateImportProgressStatus(importEvent.getImportContext().getAsyncKey(), subTaskKey, ImportTaskLifecycle.BATCH_DATA_PULLED);
                        log.error("unSerializable data start handle time = {}", System.currentTimeMillis() - startTime);
                        int processCount = importEvent.getProcessCount();
                        processCount = mapList.size();
                        importEvent.setProcessCount(processCount);
                        importContext.setViewModel(viewModel);
                        importContext = this.converService.importContextDto2ImportContext(contextDto, tenantCode, viewModel, importContext);
                        importContext.setNeedReady4AssemGrandchild(false);
                        totalCount = importContext.getTotalCount();
                        importContext.setTotalCount(totalCount);
                        ForwardingPipeline pipeline = this.importServiceInit.getUniteEventImportPrePipeline();
                        PrePipelineContext prePipelineContext = new PrePipelineContext(importContext, mapList);
                        prePipelineContext.setEventSendTime(contextDto.getEventSendTime());
                        prePipelineContext.setTrasferResultHandled(true);
                        prePipelineContext.setSubTaskKey(subTaskKey);
                        RPCStubBeanFactory rpChainBeanFactory = new RPCStubBeanFactory("IUAP-METADATA-IMPORT", "c87e2267-1001-4c70-bb2a-ab41f3b81aa3", "", IPoiSupportApi.class);
                        rpChainBeanFactory.afterPropertiesSet();
                        IPoiSupportApi poiSupportService = DubboReferenceUtils.getDubboService(IPoiSupportApi.class, "ucf-mdf-exceltrain", null);
                        if (null != poiSupportService) {
                            Boolean supportRootErrorMessage = false;

                            try {
                                supportRootErrorMessage = poiSupportService.supportRootErrorMessage();
                            } catch (Exception var26) {
                                log.error("UniteImportEventHandle::importHandleEvent::supportRootErrorMessage报错了，应该是触发兼容了不需要处理", var26);
                            }

                            prePipelineContext.setSupportRootErrorMessage(BooleanUtils.b(supportRootErrorMessage, false));
                        }

                        pipeline.exePipeline(prePipelineContext);
                    }
                }
            } else {
                throw new BizException("get import data error from apply tool,url={}", url);
            }
        }
    }
}
